const MongoClient = require('mongodb').MongoClient;

const url = 'mongodb://localhost:27017';
const dbName = `node_test`

let getClient = () => {
    return new Promise((resolve, reject) => {
        MongoClient.connect(url, (err, client) => {
            if (err) {
                reject(err)
            } else {
                resolve(client)
            }
        })
    })
}

;(async () => {
    try {
        // 1. 连接数据库
        let clinet = await getClient();
        console.log('1. 连接数据库')

        // 2. 获取数据库实例
        const db = await clinet.db(dbName)
        console.log('2. 获取数据库实例')

        // 3. 获取集合实例
        const stations = await db.collection('stations')
        await stations.deleteMany()

        await stations.insertMany([
            { name: '天安门西', loc: [116.39807,39.913884] },
            { name: '天安门东', loc: [116.407988,39.91416] },
            { name: '王府井', loc: [116.418008,39.914427] },
        ])

        await stations.createIndex({ loc: '2dsphere' })

        let r = await stations.find({
            loc: {
                $nearSphere: { // 查询算法
                    $geometry: {
                        type: 'Point',
                        coordinates: [
                            // 地图坐标
                            // 116.405886,39.91398, // 天安门东附近
                            116.418031,39.914146 // 王府井附近
                        ]
                    },
                    $maxDistance: 1000, // 1 公里
                }
            }
        }).toArray()
        console.log('最近的地铁站',r)


        // console.log('3. 获取集合实例')

        // // 4. 插入数据
        // let r = await frutisColl.insertOne({ name: '苹果', price: 18.9 })
        // console.log('4. 插入数据', r.result)

        // // 5. 查询
        // r = await frutisColl.findOne()
        // console.log('5. 查询', r)

        // // 6. 更新
        // r = await frutisColl.updateOne(
        //     { name: '苹果' },
        //     { $set: { price: 21.9 } }
        // )
        // console.log('6. 更新')

        // // 7. 删除
        // r = await frutisColl.deleteOne({ name: '苹果' })
        // console.log('7. 删除')

    } catch (error) {
        console.log(error)
    }
})();
